$(function () {

    /*滑动验证码*/
    verifyFn('320', '160', '320');

    // 初始化 summernote 富文本编辑
    $('#content').summernote({
        height: 150,
        lang: 'zh-CN',
        toolbar: [
            //添加图片
            ['insert', ['myImage']]
        ],
        disableDragAndDrop: true,
        buttons: {
            myImage: function () {
                var target = $('#content');
                var ui = $.summernote.ui;
                var button = ui.button({
                    contents: '<i class="note-icon-picture"/>',
                    tooltip: '上传图片',
                    click: function () {
                        var winContext = '<div class="mt10 mb10 ml20 mr20">';
                        winContext += '选择图片<input type="file" id="fileInput" class="form-control"/><br/>';
                        winContext += '或填写图片路径<input class="form-control" value="" id="imageUrl" type="text"/>';
                        winContext += '</div>';
                        parent.layer.open({
                            type: 1,
                            shadeClose: false,
                            area: ['500px'],
                            skin: 'layui-layer-demo',
                            title: '插入图片',
                            content: winContext,
                            btn: '确定',
                            yes: function (index, layero) {
                                var file = layero.find("#fileInput")[0].files[0];
                                var imageUrl = layero.find("#imageUrl").val();
                                if (typeof file == 'undefined' && (imageUrl == null || $.trim(imageUrl) == '')) {
                                    icModale(0, '', "请选择图片或填写有效的图片路径");
                                    return;
                                }
                                if (imageUrl == null || $.trim(imageUrl) == '') {
                                    var fileData = new FormData();
                                    fileData.append("file", file);
                                    $.ajax({
                                        url: baseloaction + '/web/uc/upload/uploadImgFile',
                                        type: 'post',
                                        data: fileData,
                                        cache: false,
                                        contentType: false,
                                        processData: false,
                                        success: function (result) {
                                            if (result.success == true) {
                                                var imgObj = result.entity;
                                                target.summernote('insertImage', imgObj.url, function ($image) {
                                                    $image.css('width', "100%");
                                                    $image.attr("alt",imgObj.fileName);
                                                    parent.layer.close(index);
                                                });
                                            } else {
                                                icModale(0, '', result.message);
                                            }
                                        },
                                        error: function (error) {
                                            icModale(0, '', "系统错误，文件上传失败");
                                        }
                                    });
                                } else {
                                    var conditions =true;
                                    target.summernote('insertImage', imageUrl, function ($image) {
                                        $image.addClass('e-tg-txt-pic');
                                        conditions= false;
                                        parent.layer.closeAll();
                                    });
                                    if(conditions){
                                        icModale(0, '', "图片路径错误，如是本地图片请使用上传");
                                    }
                                }

                            }
                        });
                    }
                });
                return button.render();
            }
        }
    , callbacks: {
            onKeydown: function(e) {
              var  content = $('#content').summernote('code');
                if( content.replace(/<[^>]+>/g,"").length>=5000){
                    icModale(0, '', "话题详情最多输入5000个字");
                }
            }
        }});


    //下拉 select 选择标签
    $('.chosen-select').chosen();

    $('body')
        .on('click', '#topic-publish', function () {
            pretreatment();
        })
        .on('click', 'img.v-code-pic, #kaptcha-change', function () { // 更换验证码
            var src = $('img.v-code-pic').attr('src');
            src = src.split('?')[0];
            src += '?timestamps=' + new Date().getTime();
            $('img.v-code-pic').attr('src', src);
        }).on("keydown","input[name=title]",function(){
                if($(this).val().length>=50){
                    icModale(0, '', "标题最多输入50个字");
                }
        });
    // 发表话题前的一些预处理
    function pretreatment() {
        var content = $('#content').summernote('code');
        if( content.replace(/<[^>]+>/g,"").length>=5000){
            icModale(0, '', "话题详情最多输入5000个字");
            return;
        }
        //不捕获文本编辑器里的图片
     /*   var $content = $($.parseHTML(content));
        var images = $content.find('img');
        if (images.length > 0) {
            var topicImages = images.map(function () {
                return this.src;
            }).get().join(',');
            $('#topicImages').val(topicImages);
        } else {
            $('#topicImages').val('');
        }*/
        topicPublish();
    }

    // 话题发表
    function topicPublish() {
        var params = $('form.toQuestionForm').serializeJSON();
        var to= $('#content').summernote('code');
        params.content = $('#content').summernote('code');
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + '/web/classes/topic/saveTopic',
            data: params,
            dataType: 'json',
            type: 'post',
            contentType: 'application/json;charset=utf-8',
            success: function (response) {
                icModale(0, '', response.message);
                if (response.success==true) {
                    topicId = response.entity.id;
                     window.location = baseloaction + '/web/classes/topic/info?id=' + topicId;
                }
            },
            error: function () {
                icModale(0, '', '系统繁忙，请稍后再试');
            }
        })
    }
});